package mysql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"mini/config"
	"sync"
)

var (
	DB   *gorm.DB
	err  error
	once sync.Once
)

func MysqlInit() {
	appConfig := config.AppConfig.MysqlConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", appConfig.User, appConfig.Password,
		appConfig.Host, appConfig.Port, appConfig.Database)
	once.Do(func() {
		DB, err = gorm.Open(mysql.Open(dsn))
		if err != nil {
			fmt.Println("mysql连接失败")
			return
		} else {
			fmt.Println("mysql连接成功")
		}
	})
	err = DB.AutoMigrate(&Users{})
	if err != nil {
		fmt.Println("用户表迁移失败")
	} else {
		fmt.Println("用户表迁移成功")
	}
	DB.Set("gorm:users", "engine=innodb")

	err = DB.AutoMigrate(&Products{})
	if err != nil {
		fmt.Println("商品表迁移失败")
	} else {
		fmt.Println("商品表迁移成功")
	}
	DB.Set("gorm:shops", "engine=innodb")
}
